from logging import getLogger

from solr import SolrPaginator

from meercat.ui.client.compat import etree
from meercat.ui.client.utils import unicodeParameterEncoding



log = getLogger('meercat.ui.client.rest')

def solr_response(response):
    response.header['params'] = unicodeParameterEncoding(response.header['params'])
    response.paginator = SolrPaginator(response)
    return response

def rest_response(response):
    resource = etree.parse(response).getroot()
    log.debug('parsing a response: %s' % (response,))
    log.debug('parsing a resource: %s' % (resource,))
    output = {}
    output['instances'] = []
    
    for child in resource.getchildren():
        log.debug('parsing: %s' % (child,))
        if child.tag in ('instance', 'instances',):
            output['instances'].append(rest_instance(child))
            continue
        if child.tag == 'url':
            text = rest_url(child)
        else:
            text = clean_rest_value(child.text)
        
        if text:
            output.setdefault(child.tag, set()).add(text)
    
    output.setdefault('holdings',[]).extend(map(lambda u: {'url':[u]},
                                                output.get('url',[])))
    
    log.debug('parsed response to: %s' % (str(output),))
    
    return output 

def rest_instance(instance):
    output = {}
    output['holdings'] = []
    
    log.debug('parsing an instance: %s' % (instance,))
    
    for child in instance.getchildren():
        log.debug('parsing: %s' % (child,))
        if child.tag in ('holding','holdings'):
            output['holdings'].append(rest_holding(child))
            continue
        
        if child.tag == 'location':
            rest_location_code(child, output)
        
        if child.tag == 'url':
            text = rest_url(child)
        else:
            text = clean_rest_value(child.text)
        
        if text:
            output.setdefault(child.tag, set()).add(text)
    
    output.setdefault('holdings',[]).extend(map(lambda u: {'url':[u]},
                                                output.get('url',[])))
    
    return output

def rest_holding(holding):
    output = {}
    log.debug('parsing a holding: %s' % (holding,))
    for child in holding.getchildren():
        log.debug('parsing: %s' % (child,))
        if child.tag in ('copy','copies',):
            output.setdefault('copies',[]).append(rest_copy(child))
            continue
        
        if child.tag == 'location':
            rest_location_code(child, output)
        
        text = clean_rest_value(child.text)
        title = clean_rest_value(child.get('title'))
        if title and text:
            value = (title, text,)
        elif text:
            value = text
        else:
            continue
        output.setdefault(child.tag, set()).add(value)
    
    output['type'] = holding.get('type')
    output['available'] = holding.get('available').lower() in ('true','yes','1')
    
    if 'copies' in output:
        output['copies'].sort(key=lambda c: ','.join(c.get('threshold',[])))
    
    if len(output) <= 2:
        return None
    
    return output

def rest_copy(copy):
    output = {}
    log.debug('parsing a copy: %s' % (copy,))
    for child in copy.getchildren():
        text = clean_rest_value(child.text)
        
        if child.tag == 'barcode' and child.get('status').lower() != 'active':
            continue
        
        if text:
            output.setdefault(child.tag, set()).add(text)
        
        if child.tag == 'location':
            rest_location_code(child, output)
    
    output = dict(map(lambda t: (t[0],list(t[1])), output.iteritems()))
    
    if 'threshold' in output:
        output['threshold'].sort()
    
    return output

def rest_location_code(location, output={}):
    if location.get('code'):
        text = clean_rest_value(location.get('code'))
        if text:
            output.setdefault('locationCode', set()).add(text)
    return output

def rest_url(url):
    if url.tag == 'url':
        text = clean_rest_value(url.text)
        if url.get('title') and text:
            return (url.get('title'),text,)
        elif text:
            return text
    return None

def clean_rest_value(value):
    if not value:
        return
    return value.replace('\t','').strip()